package com.qimei.onerice.servlet;

import com.qimei.onerice.entity.Admin;
import com.qimei.onerice.entity.Customer;
import com.qimei.onerice.service.AdminService;
import com.qimei.onerice.service.CustomerService;
import com.qimei.onerice.service.impl.AdminServiceImpl;
import com.qimei.onerice.service.impl.CustomerServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/register")
public class RegisterServlet extends HttpServlet {
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			String identity = request.getParameter("identity");
			String username = request.getParameter("username");
			String password = request.getParameter("password");
			String name = request.getParameter("name");
			String phone = request.getParameter("phone");
			String email = request.getParameter("email");

			AdminService adminService = new AdminServiceImpl();
			CustomerService customerService = new CustomerServiceImpl();
			// 判断用户名、联系方式、邮箱是否已存在
			if (adminService.isAdminExists(username, phone, email) || customerService.isCustomerExists(username, phone, email)) {
				response.setContentType("application/json");
				response.setCharacterEncoding("UTF-8");
				response.getWriter().write("{\"error\": \"用户名、联系方式或邮箱已存在\"}");
				return;
			}

			switch (identity) {
				case "admin":
					Admin admin = new Admin();
					admin.setAdminUsername(username);
					admin.setAdminPassword(password);
					admin.setAdminName(name);
					admin.setAdminEmail(email);
					admin.setAdminPhone(phone);
					adminService.addAdmin(admin);
					handleRegisterResponse(response);
					break;
				case "customer":
					Customer customer = new Customer();
					customer.setCustomerUsername(username);
					customer.setCustomerPassword(password);
					customer.setCustomerName(name);
					customer.setCustomerEmail(email);
					customer.setCustomerPhone(phone);
					customerService.addCustomer(customer);
					handleRegisterResponse(response);
					break;
				default:
					response.setContentType("application/json");
					response.setCharacterEncoding("UTF-8");
					response.getWriter().write("{\"error\": \"未选择身份\"}");
					break;
			}
		} catch (Exception e) {
			e.printStackTrace();
			response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "注册失败");
		}
	}

	private void handleRegisterResponse(HttpServletResponse response) throws IOException {
		// 注册成功
		response.setContentType("application/json");
		response.setCharacterEncoding("UTF-8");
		response.getWriter().write("{\"success\": true}");
	}
}
